import axios from 'axios'
const { createSlice } = require('@reduxjs/toolkit')

// 创建仓库
const foodsStore = createSlice({
  name: 'foods',
  initialState: {
    foodsList: [], // 商品列表
    activeIndex: 0, // sidetab栏切换下标
    cartList: [] // 购物车列表
  },
  reducers: {
    // reducer里面定义了一些修改state状态的actions方法
    setFoodsList(state, action) {
      state.foodsList = action.payload
    },
    setActiveIndex(state, action) {
      state.activeIndex = action.payload
    },
    // 设置购物车数据列表
    setCartlist(state, action) {
      console.log('set', state.cartList.length)
      const item = state.cartList.find((item) => {
        return item.id === action.payload.id
      })
      if (item) {
        item.count++
      } else {
        state.cartList.push(action.payload)
      }
    },
    // 清空购物车
    clearCartList(state) {
      state.cartList = []
    },
    // 增加商品数目
    increase(state, action) {
      const item = state.cartList.find((item) => item.id === action.payload.id)
      item.count++
    },
    // 减少商品数目
    decrease(state, action) {
      const item = state.cartList.find((item) => item.id === action.payload.id)
      if (item.count === 0) return
      item.count--
    }
  }
})

const { setFoodsList, setActiveIndex, setCartlist, clearCartList, increase, decrease } =
  foodsStore.actions
// 异步获取部分
const fetchFoodsList = () => {
  return async (dispatch) => {
    const res = await axios.get('http://localhost:3004/takeaway')
    // 调用dispatch函数提交action
    dispatch(setFoodsList(res.data))
  }
}
const reducer = foodsStore.reducer

export { fetchFoodsList, setActiveIndex, setCartlist, clearCartList, increase, decrease }
export default reducer
